package com.eascs.workflow.sys.controller;

import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.eascs.app.dao.PageResult;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.util.StringUtil;
import com.eascs.common.util.UrlUtil;
import com.eascs.site.controller.BaseRestController;
import com.eascs.site.page.PaginationInfo;
import com.eascs.site.page.SelectDataOption;
import com.eascs.site.view.BaseRestResult;
import com.eascs.site.view.HtmlRestResult;
import com.eascs.site.view.PaginationRestResult;
import com.eascs.site.view.ViewContext;
import com.eascs.site.view.button.Button;
import com.eascs.site.view.button.ButtonHelper;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;
import com.eascs.workflow.aging.entity.ProcessInfoEntity;
import com.eascs.workflow.sys.dao.HREmplAuditorDao;
import com.eascs.workflow.sys.entity.HREmployeeAuditorEntity;
import com.eascs.workflow.sys.service.HREmplAuditorService;
import com.eascs.workflow.sys.service.PubDditemService;
import com.eascs.workflow.sys.vo.HREmployeeAuditor;

/**
 * 人员关系维护
 * 
 * @author LMX
 *
 */
@RestController
@RequestMapping("/rHREmplAuditor")
public class HREmplAuditorRestController extends BaseRestController {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private HREmplAuditorService hrEmplAuditorService;
	@Autowired
	private PubDditemService pubDditemService;
	@Autowired
	HREmplAuditorDao hrEmplAuditorDao;

	@RequestMapping("/o2o")
	public PaginationRestResult findPageO2oData(HREmployeeAuditor entity) {
		entity.setPageSize(20);
		PageResult<Object[]> pageResult = hrEmplAuditorService.findO2oByPage(entity);
		String titles[] = { "姓名", "关系", "关系人", "操作人", "最后更新时间" };
		SelectDataOption[] selectDataOptions = { null, null, null, null, null, null };
		String url = "/rHREmplAuditor/o2o";
		String employeeName = entity.getEmployeeName() == null ? "" : entity.getEmployeeName();
		String auditorType = entity.getAuditorType() == null ? "" : entity.getAuditorType();
		String auditorName = entity.getAuditorName() == null ? "" : entity.getAuditorName();
		url = UrlUtil.appendUrl(url, "employeeName", employeeName);
		url = UrlUtil.appendUrl(url, "auditorType", auditorType);
		url = UrlUtil.appendUrl(url, "auditorName", auditorName);
		url = url + "&o2oIndex=";
		PaginationInfo pagingInfo = new PaginationInfo(pageResult, titles, url);
		Button buttonEdit = ButtonHelper.createAjaxButton("编辑", "/rHREmplAuditor/edit_view?employeeAuditorNo=");
		Button buttonDelete = ButtonHelper.createAjaxConfirmButton("删除",
				"/rHREmplAuditor/deleteHrEmplAuditor?employeeAuditorNo=");
		Button[] titleButtons = new Button[] { buttonEdit, buttonDelete };
		pagingInfo.setMoreButtons(titleButtons);
		pagingInfo.setBuildPagingNavigation(true);
		pagingInfo.setBuildSelectBox(true);
		pagingInfo.setSelectDataOptions(selectDataOptions);
		pagingInfo.setFirstRenderColumnIndex(1);
		pagingInfo.setRendTo("#o2o_result");// 跳转到id位o2o_result的目标模板中！！！局部刷新！！！
		ViewContext.put("vo", entity);
		return PaginationRestResult.buildPaginationRestResult(pagingInfo);
	}

	@RequestMapping("/setupPopup")
	public BaseRestResult<?> upoa(HttpServletRequest request) {
		String[] billCode = request.getParameterValues("ids");
		if (billCode == null || billCode.length == 0) {
			return BaseRestResult.info("请至少选择一个用户");
		}
		StringBuffer billcode_update = new StringBuffer();
		for (int i = 0; i < billCode.length; i++) {
			billcode_update.append(billCode[i] + ",");
		}
		String billcode_update_ = billcode_update.substring(0, billcode_update.length() - 1);
		ViewContext.put("ids", billcode_update_);
		return HtmlRestResult.popHtmlFragment("user/setupPopup");
	}

	@RequestMapping(value = "/saveSetup", method = RequestMethod.POST)
	public BaseRestResult<String> saveArchiveRecords(String ids, String auditorNo, String auditorName) {
		User user = UserHolder.getUser();
		try {
			Boolean result = false;
			String[] idsArr = ids.split(",");
			for (String employNo : idsArr) {
				result = hrEmplAuditorDao.updateEmployeeEntity(employNo, auditorNo, auditorName, user);
				if (!result) {
					throw new RuntimeException("数据修改失败");
				}
			}
			return BaseRestResult.info("修改成功").buildClosestReloadResult();
		} catch (Exception e) {
			logger.info("修改失败:", e);

		}
		return BaseRestResult.info("修改失败");
	}

	/**
	 * 批量删除
	 * 
	 * @param employeeAuditorNo
	 * @return
	 */
	@RequestMapping("/batchDeleteHrEmplAuditor")
	public BaseRestResult<?> batchDeleteHrEmplAuditor(HttpServletRequest request) {
		String[] employeeAuditorNos = request.getParameterValues("ids");
		if (employeeAuditorNos == null || employeeAuditorNos.length == 0) {
			return BaseRestResult.info("请至少选择一个用户");
		}

		for (String employeeAuditorNo : employeeAuditorNos) {
			HREmployeeAuditorEntity hrEmployeeAuditorEntity = hrEmplAuditorService
					.getHREmployeeAuditorEntityByNo(employeeAuditorNo);
			hrEmployeeAuditorEntity.setIs_del("Y");// 设置删除标记为Y
			hrEmployeeAuditorEntity.setOp_psnNo(UserHolder.getUser().getNo());// 设置操作人id
			hrEmployeeAuditorEntity.setOp_psn(UserHolder.getUser().getCname());// 设置操作人
			hrEmployeeAuditorEntity.setOp_date(new Date());// 设置操作时间(最后更新时间)
			hrEmplAuditorService.deleteHrEmplAuditor(hrEmployeeAuditorEntity);
		}
		return BaseRestResult.info("删除成功").andRefresh();
	}

	/**
	 * 伪删除-删除人员关系信息
	 * 
	 * @author LMX
	 * @param employeeAuditorNo
	 * @return
	 */
	@RequestMapping("/deleteHrEmplAuditor")
	public BaseRestResult<?> deleteHrEmplAuditor(String employeeAuditorNo) {
		HREmployeeAuditorEntity hrEmployeeAuditorEntity = hrEmplAuditorService
				.getHREmployeeAuditorEntityByNo(employeeAuditorNo);
		boolean flag = false;
		BaseRestResult<?> result = null;
		hrEmployeeAuditorEntity.setIs_del("Y");// 设置删除标记为Y
		hrEmployeeAuditorEntity.setOp_psnNo(UserHolder.getUser().getNo());// 设置操作人id
		hrEmployeeAuditorEntity.setOp_psn(UserHolder.getUser().getCname());// 设置操作人
		hrEmployeeAuditorEntity.setOp_date(new Date());// 设置操作时间(最后更新时间)
		flag = hrEmplAuditorService.deleteHrEmplAuditor(hrEmployeeAuditorEntity);
		if (flag == true) {
			result = BaseRestResult.info("删除成功").andRefresh();
		} else if (flag == false) {
			result = BaseRestResult.error("删除失败");
		}
		return result;
	}

	/**
	 * 跳转到修改人员关系界面
	 * 
	 * @author LMX
	 * @param employeeAuditorNo
	 * @return
	 */
	@RequestMapping("/edit_view")
	public BaseRestResult<String> editView(String employeeAuditorNo) {
		HREmployeeAuditor vo = hrEmplAuditorService.getHrEmplAuditorByNo(employeeAuditorNo);
		ViewContext.put("vo", vo);
		return HtmlRestResult.popHtmlFragment("/user/edit_hrEmplAuditor");
	}

	/**
	 * 修改/编辑人员关系信息
	 * 
	 * @author LMX
	 * @param entity
	 * @return
	 */
	@RequestMapping("/edit_save")
	public BaseRestResult<String> editSave(HREmployeeAuditor entity) {
		BaseRestResult<String> results = null;
		// boolean flag = false;
		if (StringUtils.isEmpty(entity.getEmployeeName())) {
			results = BaseRestResult.warn("姓名为空，请输入");
		} else if (StringUtils.isEmpty(entity.getAuditorType())) {
			results = BaseRestResult.warn("关系为空，请选择");
		} else if (StringUtils.isEmpty(entity.getAuditorName())) {
			results = BaseRestResult.warn("关系人为空，请输入");
		} else {
			if (entity.getEmployeeNo().equals(entity.getAuditorNo())) {
				return results = BaseRestResult.warn("关系人不能为本人");
			}

			HREmployeeAuditorEntity hrEmployeeAuditorEntity = hrEmplAuditorService
					.getHrEmplAuditor(entity.getEmployeeAuditorNo());
			if (hrEmployeeAuditorEntity != null) {
				hrEmployeeAuditorEntity.setAuditorType(entity.getAuditorType());
				hrEmployeeAuditorEntity.setAuditorNo(entity.getAuditorNo());
				hrEmployeeAuditorEntity.setAuditorName(entity.getAuditorName());
				hrEmployeeAuditorEntity.setOp_psnNo(UserHolder.getUser().getNo());// 设置操作人id
				hrEmployeeAuditorEntity.setOp_psn(UserHolder.getUser().getCname());// 设置操作人
				hrEmployeeAuditorEntity.setOp_date(new Date());// 设置操作时间(最后更新时间)
				int i = hrEmplAuditorService.update(hrEmployeeAuditorEntity);
				if (i > 0) {
					return results = BaseRestResult.info("保存成功").andRefresh();
				} else {
					return results = BaseRestResult.error("保存失败");
				}
			}
		}
		return BaseRestResult.error("保存失败");
	}

	/**
	 * 跳转到添加人员关系界面
	 * 
	 * @author LMX
	 * @param employeeAuditorNo
	 * @return
	 */
	@RequestMapping("/add_view")
	public BaseRestResult<String> addview() {
		return HtmlRestResult.popHtmlFragment("user/add_hrEmplAuditor");
	}

	/**
	 * 添加人员关系信息
	 * 
	 * @author LMX
	 * @param entity
	 * @param employeeAuditorNo
	 * @return
	 */
	@RequestMapping("/add_save")
	public BaseRestResult<String> addSave(HREmployeeAuditor entity) {
		BaseRestResult<String> results = null;
		// boolean flag = false;
		if (StringUtils.isEmpty(entity.getEmployeeName())) {
			results = BaseRestResult.warn("姓名为空，请输入");
		} else if (StringUtils.isEmpty(entity.getAuditorType())) {
			results = BaseRestResult.warn("关系为空，请选择");
		} else if (StringUtils.isEmpty(entity.getAuditorName())) {
			results = BaseRestResult.warn("关系人为空，请输入");
		} else {
			if (!entity.getEmployeeNo().equals(entity.getAuditorNo())) {
				HREmployeeAuditorEntity B = hrEmplAuditorService.getEmployeeEntity(entity.getEmployeeNo(),
						entity.getAuditorType(), entity.getAuditorNo());
				if (B != null) {
					return BaseRestResult.warn("该人员关系已存在，无需重复添加");
				}

				if (!StringUtils.equalsIgnoreCase(entity.getAuditorType(), "CE")) {
					List<HREmployeeAuditorEntity> A = hrEmplAuditorService.getEmployeeEntity(entity.getEmployeeNo(),
							entity.getAuditorType());
					if (!CollectionUtils.isEmpty(A)) {
						ProcessInfoEntity p = pubDditemService.queryPubDditem("12", A.get(0).getAuditorType());// 查数据字典--所属关系，type='12'
						String warnInfo = A.get(0).getEmployeeName() + " 已添加" + p.getProcedureName() + "关系人";
						return results = BaseRestResult.warn(warnInfo);
					}
				}

				HREmployeeAuditorEntity hrEmployeeAuditorEntity = new HREmployeeAuditorEntity();
				// hrEmployeeAuditorEntity.setEmployeeAuditorNo(entity.getEmployeeAuditorNo());//添加不需要,自动生成Id
				hrEmployeeAuditorEntity.setEmployeeNo(entity.getEmployeeNo());
				hrEmployeeAuditorEntity.setAuditorNo(entity.getAuditorNo());
				hrEmployeeAuditorEntity.setEmployeeName(entity.getEmployeeName());
				hrEmployeeAuditorEntity.setAuditorName(entity.getAuditorName());
				hrEmployeeAuditorEntity.setAuditorType(entity.getAuditorType());
				hrEmployeeAuditorEntity.setIs_del("N");// 未删除标记
				hrEmployeeAuditorEntity.setOp_psnNo(UserHolder.getUser().getNo());// 设置操作人id
				hrEmployeeAuditorEntity.setOp_psn(UserHolder.getUser().getCname());// 设置操作人
				hrEmployeeAuditorEntity.setOp_date(new Date());// 设置操作时间(最后更新时间)
				HREmployeeAuditorEntity after = hrEmplAuditorService.saveEmployeeAuditor(hrEmployeeAuditorEntity);
				if (StringUtil.isNotBlank(after.getAuditorNo())) {
					return results = BaseRestResult.info("保存成功").andRefresh();
				} else {
					return results = BaseRestResult.error("保存失败");
				}
			} else {
				return results = BaseRestResult.warn("关系人不能为本人");
			}
		}
		return results;
	}

}
